<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
</head>
<body>
<h1>添加新用户</h1>
<form id="userForm">
    <label for="username">用户名:</label>
    <input type="text" id="username" name="username" required><br><br>

    <label for="password">密码:</label>
    <input type="password" id="password" name="password" required><br><br>

    <label for="department">部门名称:</label>
    <select id="department" name="department" required>
        <!-- 部门选项将通过 JavaScript 动态加载 -->
    </select><br><br>

    <label for="user">用户信息:</label>
    <input type="text" id="user" name="user" required><br><br>

    <button type="submit">添加用户</button>
</form>

<div id="result"></div>

<script>
    // 获取部门列表并填充下拉栏
    fetch('/api/departments/listAll')
        .then(response => response.json())
        .then(departments => {
            const departmentSelect = document.getElementById('department');

            departments.forEach(department => {
                const option = document.createElement('option');
                option.value = department.id; // 假设 department 对象中有 id 属性
                option.dataset.level = department.level; // 存储 level 值
                option.textContent = department.department_name; // 假设 department 对象中有 department_name 属性
                departmentSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error fetching departments:', error);
        });

    document.getElementById('userForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const formData = new FormData(this);
        const departmentSelect = document.getElementById('department');
        const selectedOption = departmentSelect.options[departmentSelect.selectedIndex];

        const userData = {
            username: formData.get('username'),
            password: formData.get('password'),
            department_name: selectedOption.textContent, // 获取部门名称
            user: formData.get('user'),
            level: parseInt(selectedOption.dataset.level) // 获取 level 值
        };

        fetch('/api/AddUsers', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(userData)
        })
            .then(response => response.text())
            .then(data => {
                document.getElementById('result').innerText = data;
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('result').innerText = '发生错误，请重试';
            });
    });
</script>
</body>
</html>
